package aishua.com.mytestapplist;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import aishua.com.mytestapplist.apdu.MyApduAdapter;
import aishua.com.mytestapplist.bean.ResAppletApduChatBean;
import aishua.com.mytestapplist.coredata.ApduInfo;
import aishua.com.mytestapplist.engin.WebServiceConnection;
import aishua.com.mytestapplist.janshe.JiansheCirView;
import aishua.com.mytestapplist.utils.CTWalletLog;
import aishua.com.mytestapplist.utils.CommonMethods;
import aishua.com.mytestapplist.utils.LogUtils;
import aishua.com.mytestapplist.utils.CrashHandler;

/**
 * Created by aishua on 2017/5/18.
 */

public class JianSheActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "JianSheActivity-";
    private JiansheCirView jiansheCirView;
    private Button btnDownapplet;
    private MyApduAdapter myapduadapter;
    private int[] ImageViewID;
    private String[] texts;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        CrashHandler.getInstance().init(this);
        setContentView(R.layout.activity_jianshe);
        jiansheCirView = (JiansheCirView) findViewById(R.id.jscirView);
        texts = new String[]{"信用卡", "安全中心", "特色服务", "投资理财", "转账汇款", "我的账户"};
        ImageViewID = new int[]{R.drawable.bgitem, R.drawable.bgitem, R.drawable.bgitem, R.drawable.bgitem, R.drawable.bgitem, R.drawable.bgitem, R.drawable.bgitem};
        jiansheCirView.setItemMenu(ImageViewID, texts);
        jiansheCirView.setOnItemOnclickListener(new JiansheCirView.ItemOnclickListener() {
            @Override
            public void onclick(View view, int pos) {

                Toast.makeText(JianSheActivity.this, texts[pos], Toast.LENGTH_SHORT).show();
            }
        });
        btnDownapplet = (Button) findViewById(R.id.btnDownapplet);
        btnDownapplet.setOnClickListener(this);
        String result = hexStringToString("3130303037353130393130323333323236303736");
        LogUtils.v(TAG + "result:" + result);

    }

    @Override
    public void onClick(View v) {

        //第二个参数是应用版本号
        new Thread() {
            @Override
            public void run() {

//                dispatherSeOpr(MyApplication.oprAID, "6");
                myapduadapter = MyApduAdapter.getDefaultAdapter(JianSheActivity.this);
                myapduadapter.initEdepAdapter("A00000000386980701");

            }
        }.start();
//        sendSMS();
    }

    private void sendSMS() {

        SmsManager sms = SmsManager.getDefault();

        Class smClass = SmsManager.class;
        //通过反射查到了SmsManager有个叫做mSubId的属性
        Field field = null;
        try {
            field = smClass.getDeclaredField("mSubId");
            field.setAccessible(true);
            field.set(sms, 1);//0:默认卡1发送；1：默认卡2发送

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(), 0);
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage("15210012925", null, "郭总真帅", pendingIntent, null);
    }

    public void dispatherSeOpr(String oprAID, String oprAppletVersion) {


        WebServiceConnection connection = WebServiceConnection.getInstant(this);
        // 平台返回的apdu命令集，用来请求卡片
        List<ApduInfo> cApduList = null;
        // 卡片返回的apdu命令集，用来请求平台
        List<ApduInfo> rApduList = null;
        String finishTag = "";
        ResAppletApduChatBean resBean = null;
        short requestIndex = 0;
        String result = "0";
        while (!"00".equals(finishTag)) {
            requestIndex++;
            try {
                resBean = connection.doAppletApduChat(oprAID, oprAppletVersion, "01", rApduList, requestIndex, result);
                if (resBean == null) {
                    LogUtils.v(TAG + "resBean--->" + resBean);
                    return;
                }
                // 实例化平台返回的apdu
                cApduList = resBean.getResApduInfoList();
                finishTag = resBean.getFinishFlag();
                if (cApduList == null || cApduList.size() == 0) {
                    continue;
                }
                // 实例化卡片返回的apdu对象，用来下一次循环请求平台
                rApduList = new ArrayList<ApduInfo>(cApduList.size());
                for (int i = 0; i < cApduList.size(); i++) {
                    ApduInfo rApduInfo = new ApduInfo();
                    if (cApduList.get(i).getApdu() == null || cApduList.get(i).getApdu().length() == 0) {
                        List<String> swList = rApduInfo.getSwList();
                        if (swList != null) {
                            swList.clear();
                        } else {
                            swList = new ArrayList<String>();
                        }
                        swList.add("");
                        rApduInfo.setSwList(swList);
                        rApduInfo.setApdu("");
                        rApduInfo.setIndex(i);
                        rApduList.add(rApduInfo);
                        result = "1";
                        continue;
                    }

                    if (cApduList.get(i).getApdu().substring(0, 4).equalsIgnoreCase("00A4")) {
                        String cmd = "";
                        String res = "";
                        // 选择安全域名
                        try {
                            // CTWalletLog.print(
                            // "APDU TRANSMIT Sellect element:",
                            // cApduList.get(i).getApdu());
                            CTWalletLog.print(TAG + "dispatherSeOpr()-APDU TRANSMIT Sellect element:" + cApduList.get(i).getApdu());
                            // 得到当前index从平台响应回的apdu值
                            cmd = cApduList.get(i).getApdu();

                            // 得到当前index的apdu所携带的数据长度
                            int length = CommonMethods.str2byte(cmd.substring(8, 10));
                            // 根据数据指令打开逻辑通道
                            MyApduAdapter myapduadapter = MyApduAdapter.getDefaultAdapter(this);
                            LogUtils.v(TAG + "cmd.substring(10, 10 + 2 * length)--->" + cmd.substring(10, 10 + 2 * length));
                            res = myapduadapter.initEdepAdapter(cmd.substring(10, 10 + 2 * length));

                            CTWalletLog.print(TAG + "dispatherSeOpr() getSelectResponse:" + res);


                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            res = "";
                        }
                        boolean apduRightTag = false;
                        if (!res.equals("")) {
                            // 如果从卡片响应回的apdu指令尾部sw状态码 跟
                            // 平台期望的sw状态码相同，则表示当前握手成功
                            for (int k = 0; k < cApduList.get(i).getSwList().size(); k++) {
                                if (res.endsWith(cApduList.get(i).getSwList().get(k))) {
                                    apduRightTag = true;
                                    break;
                                }
                            }
                        }
                        if (!apduRightTag) {
                            rApduInfo.setApdu("");
                            List<String> swList = rApduInfo.getSwList();
                            if (swList != null) {
                                swList.clear();
                            } else {
                                swList = new ArrayList<String>();
                            }
                            if (res.length() < 4) {
                                swList.add("");
                            } else {
                                swList.add(res.substring(res.length() - 4, res.length()));
                            }
                            if ("".equals(res.substring(0, res.length() - 4))) {
                                rApduInfo.setApdu(cApduList.get(i).getApdu());
                            }
                            rApduInfo.setSwList(swList);
                            rApduInfo.setIndex(cApduList.get(i).getIndex());
                            rApduList.add(rApduInfo);
                            result = "1";
                            break;
                        } else {
                            List<String> swList = rApduInfo.getSwList();
                            if (swList != null) {
                                swList.clear();
                            } else {
                                swList = new ArrayList<String>();
                            }
                            if (res.length() < 4) {
                                swList.add("");
                            } else {
                                swList.add(res.substring(res.length() - 4, res.length()));
                            }
                            rApduInfo.setSwList(swList);
                            rApduInfo.setApdu(res.substring(0, res.length() - 4));
                            rApduInfo.setIndex(cApduList.get(i).getIndex());
                            // rApduList.add(rApduInfo);
                        }
                    } else {
                        // 指令交互
                        String cardRes = null;
                        try {
                            // CTWalletLog.print("APDU TRANSMIT CMD:",
                            // cApduList.get(i).getApdu());
                            CTWalletLog.print(TAG + "dispatherSeOpr()-APDU TRANSMIT CMD:" + cApduList.get(i).getApdu());
                            // 根据平台响应回的apdu指令 来请求卡片，得到卡片响应回的apdu数组数据
                            MyApduAdapter myapduadapter = MyApduAdapter.getDefaultAdapter(this);
                            cardRes = myapduadapter.sendApdu((cApduList.get(i).getApdu()));

                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        // 卡片响应回的apdu指令
                        String apduRes = cardRes;
                        // CTWalletLog.print("APDU TRANSMIT RES:",
                        // apduRes);
                        CTWalletLog.print(TAG + "dispatherSeOpr()-APDU TRANSMIT RES:" + apduRes);
                        rApduInfo.setIndex(cApduList.get(i).getIndex());
                        // 给向平台请求的apdu指令赋值
                        rApduInfo.setApdu(apduRes.substring(0, apduRes.length() - 4));
                        List<String> swList = rApduInfo.getSwList();
                        if (swList != null) {
                            swList.clear();
                        } else {
                            swList = new ArrayList<String>();
                        }
                        // 给当前从卡片响应回的apdu指令sw状态码赋值
                        swList.add(apduRes.substring(apduRes.length() - 4, apduRes.length()));
                        rApduInfo.setSwList(swList);
                        // 如果从卡片响应回的apdu指令尾部sw状态码 跟 平台期望的sw状态码相同，则表示当前握手成功
                        boolean apduRightTag = false;
                        for (int k = 0; k < cApduList.get(i).getSwList().size(); k++) {
                            if (apduRes.endsWith(cApduList.get(i).getSwList().get(k))) {
                                apduRightTag = true;
                                break;
                            }
                        }

                        if (!apduRightTag) {
                            if ("".equals(apduRes.substring(0, apduRes.length() - 4))) {
                                rApduInfo.setApdu(cApduList.get(i).getApdu());
                            }
                            rApduList.add(rApduInfo);
                            result = "1";
                            break;
                        }

                        // sendSeOprMsg(oprAID, oprType,
                        // GenericConstant.SE_OPR_STATUS_UPDATE,
                        // oprProgress);
                    }
                    // 传输结束
                    if (i == cApduList.size() - 1) {
                        result = "0";
                        rApduList.add(rApduInfo);
                    }

                }
            } catch (Exception e) {

                e.printStackTrace();
            }

        }
    }

    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "gbk");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }
}
